//
//  HKUIUtils.m
//  HKOnLine
//


#import "HKUIUtils.h"
#import <CommonCrypto/CommonDigest.h>
#import <QuartzCore/QuartzCore.h>
#import "LSYNLineView.h"

#define MARK_ROUND (20.f)

inline NSString *setupMD5StringForKey(NSString *key) {
    const char *str = [key UTF8String];
    if (str == NULL) {
        str = "";
    }
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                          r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
    
    return filename;
}

inline UIColor *colorWithHexAndAlpha(long hexColor, float opacity)
{
    float red = ((float)((hexColor & 0xFF0000) >> 16))/255.0;
    float green = ((float)((hexColor & 0xFF00) >> 8))/255.0;
    float blue = ((float)(hexColor & 0xFF))/255.0;
    return [UIColor colorWithRed:red green:green blue:blue alpha:opacity];
}

inline UIColor *colorWithHex(long hexColor)
{
    return colorWithHexAndAlpha(hexColor, 1.f);
}

//清除小数点
inline NSString* removeDecWith(NSString *str)
{
    const char* strCs = [str UTF8String];
    char strDec[512]={0};
    bool isDec = NO;
    
    strcpy(strDec, strCs);
    for(int i=0;i<strlen(strCs);i++)
    {
        if(strCs[i]=='.')
        {
            isDec = YES;
            break;
        }
    }
    
    if(isDec)
    {
        for(long i=strlen(strDec)-1;i>0;i--)
        {
            if(strDec[i]=='0')
                strDec[i]='\0';
            else
                break;
        }
        long len = strlen(strDec);
        if(strDec[len-1] == '.')
            strDec[len-1] = '\0';
    }
    
    return [NSString stringWithFormat:@"%s",strDec];
}

inline NSString *downCountToWanString(NSInteger count)
{
    //	以 下载/评论 次数范围为判断条件：
    //	1）	当小于1w时，显示具体数字，如 3458次下载/评论；
    //	2）	当大于等于1w小于9.95w时，四舍五入显示小数点后一位数字，如 9.9万次下载/评论；
    //	3）	当大于等于9.95w小于1亿时，四舍五入只显示整数位数字，如 19万次下载/评论；
    //	4）	当大于等于1亿小于9.95亿时，四舍五入显示小数点后一位数字，如 1.9亿次下载/评论；
    //	5）	当大于等于9.95亿时，四舍五入只显示整数位数字，如 19亿次下载/评论。
    
    NSInteger tenThoudand = 10000;
    char buff[128] = {0};
    char unit[10] = {0};
    
    if(count < 1 * tenThoudand)
    {
        //当小于1w时
        
        sprintf(buff, "%f", (double)count);
    }
    else if(count < 9.95 * tenThoudand)
    {
        //当大于等于1w小于9.95w时
        
        sprintf(buff, "%.1f", (double)((double)count/(double)(1 * tenThoudand)));
        strcpy(unit, "万");
    }
    else if(count < 1 * tenThoudand * tenThoudand)
    {
        //当大于等于9.95w小于1亿时
        
        sprintf(buff, "%.1f", (double)((double)count/(double)(1 * tenThoudand)));
        strcpy(unit, "万");
    }
    else if(count < 9.95 * tenThoudand * tenThoudand)
    {
        //当大于等于1亿小于9.95亿时
        
        sprintf(buff, "%.1f", (double)((double)count/(double)(1 * tenThoudand * tenThoudand)));
        strcpy(unit, "亿");
    }
    else
    {
        //当大于等于9.95亿时
        
        sprintf(buff, "%.1f", (double)((double)count/(double)(1 * tenThoudand * tenThoudand)));
        strcpy(unit, "亿");
    }
    
    double dCount = atof(buff);
    sprintf(buff, "%g%s", dCount, unit);
    
    return [NSString stringWithUTF8String:buff];
    
}

inline NSString *pariseCountString(NSInteger count)
{
    //new 点赞逻辑  超过99 显示99+
    if (count > 99) {
        return @"99+";
    }
    return [NSString stringWithFormat:@"%@",[@(count)stringValue]];
}

inline NSString *detailPariseCountString(NSInteger count)
{
    //详情点赞逻辑  超过1w 显示1w+
    if (count > 10000) {
        return @"1w+";
    }
    if (count <= 0) {
        count = 0;
    }
    return [NSString stringWithFormat:@"%@",[@(count)stringValue]];
}

inline NSString *detailViewCountString(NSString *countStr)
{
    //详情浏览数  超过1w 显示1w+
    if ([countStr integerValue] > 10000) {
        return @"1w+";
    }
    if ([countStr integerValue] <= 0 || !countStr) {
        countStr = @"0";
    }
    return countStr;
}
extern NSString *detailReplyCountString(NSString *countStr)
{
    //详情回复数  超过1w 显示1w+
    if ([countStr integerValue] > 10000) {
        return @"1w+";
    }
    if ([countStr integerValue] <= 0 || !countStr) {
        countStr = @"0";
    }
    
    return countStr;
}
extern NSString *messageRedCountString(NSString *countStr)
{
    //详情回复数  超过1w 显示1w+
    if ([countStr integerValue] > 100) {
        return @"100+";
    }
    if ([countStr integerValue] <= 0 || !countStr) {
        countStr = @"0";
    }
    
    return countStr;
}

extern NSString *circleHotCountString(NSString *countStr)
{
    //详情回复数  超过1w 显示1w+
    if ([countStr integerValue] > 100000) {
        return @"10w+";
    }
    if ([countStr integerValue] <= 0 || !countStr) {
        countStr = @"0";
    }
    
    return countStr;
}

//inline NSString *fileSizeToWanString(NSInteger size)
//{
//	NSInteger theMB = 1024 * 1024;
//	char buff[128] = {0};
//	char unit[10] = {0};
//
//	if(size < 1 * theMB)
//	{
//		//小于1KB
//
//		sprintf(buff, "%f", (double)size);
//		strcpy(unit, "Byte");
//	}
//	if(size < 1 * theMB * theMB)
//	{
//		//当小于1M时
//
//		sprintf(buff, "%f", (double)((double)size/(double)1024));
//		strcpy(unit, "KB");
//	}
//	else if(size < 9.95 * theMB * theMB)
//	{
//		//当大于等于1M小于9.95M时
//
//		sprintf(buff, "%.1f", (double)((double)size/(double)(1 * theMB)));
//		strcpy(unit, "MB");
//	}
//	else if(size < 1 * theMB * theMB * theMB)
//	{
//		//当大于等于9.95M小于G亿时
//
//		sprintf(buff, "%.0f", (double)((double)size/(double)(1 * theMB)));
//		strcpy(unit, "MB");
//	}
//	else if(size < 9.95 * theMB * theMB * theMB)
//	{
//		//当大于等于1G小于9.95G时
//
//		sprintf(buff, "%.1f", (double)((double)size/(double)(1 * theMB * theMB)));
//		strcpy(unit, "GB");
//	}
//	else
//	{
//		//当大于等于9.95G时
//
//		sprintf(buff, "%f.0", (double)((double)size/(double)(1 * theMB * theMB)));
//		strcpy(unit, "GB");
//	}
//
//	double dCount = atof(buff);
//	sprintf(buff, "%g%s", dCount, unit);
//
//	return [NSString stringWithUTF8String:buff];
//}

BOOL checkSuffix(NSString *str ,NSString *suffix)
{
    BOOL ret = NO;
    
    const char *corgSuffix = str.UTF8String;
    char *cSuffix = (char *)calloc(((size_t)[str lengthOfBytesUsingEncoding:NSUTF8StringEncoding]), sizeof(char));
    
    for(int i=0; corgSuffix[i] != 0; i++)
    {
        if((corgSuffix[i] >= 'a' && corgSuffix[i] <= 'z') ||
           (corgSuffix[i] >= 'A'&& corgSuffix[i] <= 'Z'))
        {
            sprintf(cSuffix ,"%s%c", cSuffix, corgSuffix[i]);
        }
    }
    
    ret = [[NSString stringWithUTF8String:cSuffix] isEqualToString:suffix];
    
    if(cSuffix)
    {
        free(cSuffix);
    }
    
    return ret;
}

inline CGFloat floatValueFromHumanityString(NSString *sizeString, NSInteger trailUnitLength)
{
    CGFloat resultValue = 0.0f;
    
    if (([sizeString rangeOfString:@"Byte" options:NSCaseInsensitiveSearch].location != NSNotFound) ||
        checkSuffix(sizeString, @"B")) {
        [sizeString stringByReplacingOccurrencesOfString:@"Byte"
                                              withString:@""
                                                 options:NSCaseInsensitiveSearch
                                                   range:NSMakeRange(0, sizeString.length)];
        [sizeString stringByReplacingOccurrencesOfString:@"B"
                                              withString:@""
                                                 options:NSCaseInsensitiveSearch
                                                   range:NSMakeRange(0, sizeString.length)];
        
        resultValue = [sizeString floatValue];
    }else if (([sizeString rangeOfString:@"KB" options:NSCaseInsensitiveSearch].location != NSNotFound) ||
              checkSuffix(sizeString, @"K")) {
        [sizeString stringByReplacingOccurrencesOfString:@"KB"
                                              withString:@""
                                                 options:NSCaseInsensitiveSearch
                                                   range:NSMakeRange(0, sizeString.length)];
        [sizeString stringByReplacingOccurrencesOfString:@"K"
                                              withString:@""
                                                 options:NSCaseInsensitiveSearch
                                                   range:NSMakeRange(0, sizeString.length)];
        
        resultValue = [sizeString floatValue]*1024;
    }else if (([sizeString rangeOfString:@"MB" options:NSCaseInsensitiveSearch].location != NSNotFound) ||
              checkSuffix(sizeString, @"M")) {
        [sizeString stringByReplacingOccurrencesOfString:@"MB"
                                              withString:@""
                                                 options:NSCaseInsensitiveSearch
                                                   range:NSMakeRange(0, sizeString.length)];
        [sizeString stringByReplacingOccurrencesOfString:@"M"
                                              withString:@""
                                                 options:NSCaseInsensitiveSearch
                                                   range:NSMakeRange(0, sizeString.length)];
        
        resultValue = [sizeString floatValue]*1024*1024;
    }else if (([sizeString rangeOfString:@"GB" options:NSCaseInsensitiveSearch].location != NSNotFound) ||
              checkSuffix(sizeString, @"G")) {
        [sizeString stringByReplacingOccurrencesOfString:@"GB"
                                              withString:@""
                                                 options:NSCaseInsensitiveSearch
                                                   range:NSMakeRange(0, sizeString.length)];
        [sizeString stringByReplacingOccurrencesOfString:@"G"
                                              withString:@""
                                                 options:NSCaseInsensitiveSearch
                                                   range:NSMakeRange(0, sizeString.length)];
        
        resultValue = [sizeString floatValue]*1024*1024*1024;
    }
    
    return resultValue;
}

inline NSString* stringFormatFileSizeSmartUnit(long long size, long long totalSize)
{
    long bytes = 1024;
    NSString *fileSize = [NSString stringWithFormat:@"0.0"];
    NSString *uinit = @"";
    
    if (size < 0) {
        return fileSize;
    }
    
    if (size / (bytes * bytes * bytes) > 0 ) {
        fileSize = [NSString  stringWithFormat:@"%.1f",1.0 * size / (bytes * bytes * bytes)];
        if (totalSize / (bytes * bytes * bytes) > 0)uinit = @"GB";
    }
    else if (size / (bytes * bytes) > 0) {
        fileSize = [NSString  stringWithFormat:@"%.1f",1.0 * size / (bytes * bytes)];
        if (totalSize / (bytes * bytes) > 0)uinit = @"MB";
    }
    else if (size / bytes > 0) {
        fileSize = [NSString stringWithFormat:@"%.1f",1.0 * size / bytes];
        if (totalSize / (bytes) > 0)uinit = @"KB";
    }
    else {
        fileSize = [NSString stringWithFormat:@"%.1f",1.0 * size];
        if (totalSize > 0)uinit = @"B";
    }
    
    return [NSString stringWithFormat:@"%@%@",fileSize,uinit];
}

//按格式转变文件大小
inline NSString* stringFormatFileSize(long long size)
{
    long bytes = 1024;
    NSString *fileSize = [NSString stringWithFormat:@"0.0Byte"];
    
    if (size < 0) {
        return fileSize;
    }
    
    if (size / (bytes * bytes * bytes) > 0) {
        fileSize = [NSString  stringWithFormat:@"%.1fGB",1.0 * size / (bytes * bytes * bytes)];
    }
    else if (size / (bytes * bytes) > 0) {
        fileSize = [NSString  stringWithFormat:@"%.1fMB",1.0 * size / (bytes * bytes)];
    }
    else if (size / bytes > 0) {
        fileSize = [NSString stringWithFormat:@"%.1fKB",1.0 * size / bytes];
    }
    else {
        fileSize = [NSString stringWithFormat:@"%.1fByte",1.0 * size];
    }
    
    return fileSize;
}

inline CGFloat getSystemSize()
{
    NSDictionary *fsAttr = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil];
    CGFloat diskSize = [[fsAttr objectForKey:NSFileSystemSize] doubleValue] / 1000000000.00;
    return diskSize;
}

inline CGFloat getSystemFreeSize()
{
    NSDictionary *fsAttr = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil];
    CGFloat diskSize = [[fsAttr objectForKey:NSFileSystemFreeSize] doubleValue] / 1000000000.00;
    return diskSize;
}


/**
 *  适配5、6、6P~尺寸
 *
 *  @param plist 参数列表，尺寸依次是多少例如(@[@10,@20,@30])
 *
 *  @return 对应浮点数，例如(@[@10,@20,@30])5返回10，6返回20，6P返回30; (@[@10,@20) 5返回10，6和6P返回20; (@[@10])5、6、6P都返回10。
 */
inline CGFloat g_fitFloat(NSArray *plist)
{
    CGFloat f = 0.0f;
    
    if (plist.count) {
        switch (plist.count) {
            case 1:
            {
                f = [[plist firstObject] floatValue];
            }
                break;
            case 2:
            {
                f = IS_IPHONE_6 ? [plist[1] floatValue]:[plist[0] floatValue];
                f = IS_IPHONE_6P? [plist[1] floatValue]:f;
            }
                break;
            case 3:
            {
                f = IS_IPHONE_6 ? [plist[1] floatValue]:[plist[0] floatValue];
                f = IS_IPHONE_6P? [plist[2] floatValue]:f;
            }
                break;
            default:
                break;
        }
    }
    
    return f;
}

/**
 *  适配5、6、6P IphoneX~Pad尺寸
 *
 *  @param plist 参数列表，尺寸依次是多少例如(@[@7,@10,@20,@30])
 *
 *  @return 对应浮点数，例如(@[@7,@10,@20,@30])4/4s返回的是7 5返回10，6返回20，6P返回30; (@[@10,@20) 4s/5返回10，6和6P返回20; (@[@10])4、5、6、6P都返回10。
 */
inline CGFloat g_fitFloatWithPad(NSArray * plist){
    
    CGFloat f = 0.0f;
    
    if(plist.count){
        switch (plist.count) {
            case 1:
            {
                f = [[plist firstObject] floatValue];
            }
                break;
                
            case 2:{
                f = IS_IPHONE_5andSE ? [plist[0] floatValue] : f;
                f = IS_IPHONE_X ||  IS_IPHONE_6 || IS_IPHONE_6P ||  [PublicMethod isPad] ? [plist[1] floatValue]:f;
            }
                break;
                
            case 3:
            {
                f = IS_IPHONE_5andSE ? [plist[0] floatValue] : f;
                f = IS_IPHONE_6 ?   [plist[1] floatValue] : f;
                f = IS_IPHONE_X ||  IS_IPHONE_6P ||   [PublicMethod isPad] ?   [plist[2] floatValue] : f;
                
            }
                break;
                
            case 4:
            {
                f = IS_IPHONE_5andSE ?  [plist[0] floatValue] : f;
                f = IS_IPHONE_6 ?  [plist[1] floatValue] : f;
                f = IS_IPHONE_6P ?  [plist[2] floatValue] : f;
                f = IS_IPHONE_X ||  [PublicMethod isPad] ? [plist[3] floatValue] : f;
            }
                break;
                
            case 5:
            {
                f = IS_IPHONE_5andSE ?  [plist[0] floatValue] : f;
                f = IS_IPHONE_6 ?  [plist[1] floatValue] : f;
                f = IS_IPHONE_6P ?  [plist[2] floatValue] : f;
                f = IS_IPHONE_X ?  [plist[3] floatValue] : f;
                f = [PublicMethod isPad] ? [plist[4] floatValue] : f;
            }
                break;
                
            default:
                break;
        }
    }
    
    
    return  f;
}


/**
 *  适配ihone4, 5, 6, 6p, 以6的宽度为标准, 根据屏幕的比例进行缩放
 *
 *  @return 对应的屏幕的
 */
inline CGFloat g_fitScareOfIphone6(CGFloat f)
{
    
    CGFloat length = f;
    
    if(IS_IPHONE_6){
        return length;
    }else if (IS_IPHONE_6P){
        
        return ceilf(length * 414.0 / 375.0);
        
    }else if(IS_IPHONE_4and5){
        
        return ceilf(length * 320.0 / 375.0);
    }
    
    return ceilf(f);
}


/**
 *  适配5、6、6P~尺寸
 *
 *  @param plist 参数列表，字体大小依次是多少例如(@[@10,@20,@30])、(@[@10,@20)、(@[@10])
 *
 *  @return 返回对应字体大小,(@[@10,@20,@30])5返回10号字体，6返回20号字体，6P返回30号字体; (@[@10,@20) 5返回10号字体，6和6P返回20号字体; (@[@10])5、6、6P都返回10号字体。
 */
inline UIFont *g_fitSystemFontSize(NSArray *plist)
{
    return [UIFont systemFontOfSize:g_fitFloatWithPad(plist)];
}


/**
 *  圆角蒙版Image 缓存
 */
@interface roundMarkCacheKey : NSObject
@property (nonatomic, assign)CGSize size;
@property (nonatomic, assign)CGFloat radius;
@property (nonatomic, strong)UIColor *color;
@property (nonatomic, strong)UIImage *image;
@end

@implementation roundMarkCacheKey
@end

/**
 *  用于拉伸的UIImage图 缓存
 */
@interface lineImageCacheKey : NSObject
@property (nonatomic, assign)BOOL isVertical;
@property (nonatomic, assign)BOOL isFirstPixelOpaque;
@property (nonatomic, strong)UIColor *highlightColor;
@property (nonatomic, strong)UIImage *image;
@end

@implementation lineImageCacheKey
@end

@implementation HKUIUtils

+ (UIFont *) fitSystemUIFontWithSize:(CGFloat)size
{
    if (IS_IPHONE_6) {
        return [UIFont systemFontOfSize:size+1];
    }else if (IS_IPHONE_6P) {
        return [UIFont systemFontOfSize:size+2];
    }else {
        return [UIFont systemFontOfSize:size];
    }
}

+ (UIFont *) fitBoldSystemUIFontWithSize:(CGFloat)size
{
    if (IS_IPHONE_6) {
        return [UIFont boldSystemFontOfSize:size+1];
    }else if (IS_IPHONE_6P) {
        return [UIFont boldSystemFontOfSize:size+2];
    }else {
        return [UIFont boldSystemFontOfSize:size];
    }
}

+ (void)scrollTableViewToBottom:(UITableView *)tableView withAnimation:(BOOL)animation
{
    NSInteger lastSection = [tableView numberOfSections] - 1;
    NSInteger lastRow = [tableView numberOfRowsInSection:lastSection] - 1;
    
    while (lastRow < 0 && lastSection > 0) {
        --lastSection;
        lastRow = [tableView numberOfRowsInSection:lastSection] - 1;
    }
    
    if (lastSection < 0 && lastRow < 0)
        return;
    
    NSIndexPath *lastRowIndexPath =[NSIndexPath indexPathForRow:lastRow inSection:lastSection];
    [tableView selectRowAtIndexPath:lastRowIndexPath animated:YES
                     scrollPosition:(animation ? UITableViewScrollPositionBottom:
                                     UITableViewScrollPositionNone)];
    [tableView deselectRowAtIndexPath:lastRowIndexPath animated:NO];
}

+ (__kindof UIView *) addLineInView:(UIView *)parentView
                                top:(BOOL)isTop
                         leftMargin:(CGFloat)leftMargin
                        rightMargin:(CGFloat)rightMargin
{
    LSYNLineView *line = [[LSYNLineView alloc] initGrayLineWithFrame:CGRectMake(0, 0, parentView.width, 1) vertical:NO isFirstPixelOpaque:isTop];
    [line setTag:60];
    [parentView addSubview:line];

    if (isTop) {
        line.sd_layout
        .leftSpaceToView(parentView, leftMargin)
        .rightSpaceToView(parentView, rightMargin)
        .heightIs(1)
        .topEqualToView(parentView);
    }else{
        line.sd_layout
        .leftSpaceToView(parentView, leftMargin)
        .rightSpaceToView(parentView, rightMargin)
        .heightIs(1)
        .bottomEqualToView(parentView);
    }
    
    return line;
}

+ (__kindof CAShapeLayer *) addDottedLineView:(UIView *)parentView color:(UIColor *)color top:(BOOL)isTop leftMargin:(CGFloat)leftMargin rightMargin:(CGFloat)rightMargin{
    
    [parentView layoutSubviews];
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    [[parentView layer] addSublayer:shapeLayer];
    
    [shapeLayer setBounds:parentView.bounds];
    
    NSLog(@"---%@",NSStringFromCGRect(parentView.frame));
    
    [shapeLayer setPosition:parentView.center];
    [shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
    // 设置虚线颜色为blackColor
    [shapeLayer setStrokeColor:color.CGColor];
   // 3=线的宽度 1=每条线的间距 [shapeLayer setLineDashPattern:
//    [shapeLayer setLineWidth:1.0f];
    [shapeLayer setLineJoin:kCALineJoinRound];
     [shapeLayer setLineDashPattern: [NSArray arrayWithObjects:[NSNumber numberWithInt:8], [NSNumber numberWithInt:4], nil]];
 
    CGMutablePathRef path = CGPathCreateMutable();
    if (!isTop) {
        CGPathMoveToPoint(path, NULL, leftMargin, parentView.height *2 - 4);
        CGPathAddLineToPoint(path, NULL, parentView.width - rightMargin ,parentView.height * 2 - 4);
    }else{
            CGPathMoveToPoint(path, NULL, leftMargin, 0);
            CGPathAddLineToPoint(path, NULL, parentView.width - rightMargin,0);
    }
    
//
//    UIBezierPath *path2 = [UIBezierPath bezierPath];
//
//    [path2 moveToPoint:CGPointMake(leftMargin, parentView.height *2 - 4)];
//    [path2 addLineToPoint:CGPointMake(parentView.width - rightMargin ,parentView.height * 2 - 4)];
    
//    [path2 stroke];
    
    [shapeLayer setPath:path];
    CGPathRelease(path);
    
    return  shapeLayer;
    
}


+ (__kindof UIView *) addLineInView:(UIView *)parentView color:(UIColor *)color top:(BOOL)isTop leftMargin:(CGFloat)leftMargin rightMargin:(CGFloat)rightMargin;{
    
    
//    NSLog(@"%@", @(parentView.width));
    
    LSYNLineView *lineView = [[LSYNLineView alloc] initWithFrame:CGRectMake(0, 0, parentView.width, kBorderWidth) vertical:NO isFirstPixelOpaque:isTop lineColor:color];
    [parentView addSubview:lineView];
    
    if (isTop) {
        lineView.sd_layout
        .leftSpaceToView(parentView, leftMargin)
        .rightSpaceToView(parentView, rightMargin)
        .heightIs(1)
        .topEqualToView(parentView);
    }else{
        lineView.sd_layout
        .leftSpaceToView(parentView, leftMargin)
        .rightSpaceToView(parentView, rightMargin)
        .heightIs(1)
        .bottomEqualToView(parentView);
    }
    
    return lineView;
    
}


+ (__kindof UIView *) addEmptyViewInView:(UIView *)parentView color:(UIColor *)color top:(BOOL)isTop leftMargin:(CGFloat)leftMargin rightMargin:(CGFloat)rightMargin emptyheight:(CGFloat )emptyHeight{
    
//    HKNLineView *emptyView = [[HKNLineView alloc] initWithFrame:CGRectMake(0, 0, parentView.width, emptyHeight) vertical:NO isFirstPixelOpaque:isTop lineColor:color];
//    [parentView addSubview:emptyView];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
    [view setBackgroundColor:colorWithHex(0xf4f4f4)];
    [parentView addSubview:view];

    if (isTop) {
        view.sd_layout
        .leftSpaceToView(parentView, leftMargin)
        .rightSpaceToView(parentView, rightMargin)
        .heightIs(emptyHeight)
        .topEqualToView(parentView);
    }else{
        view.sd_layout
        .leftSpaceToView(parentView, leftMargin)
        .rightSpaceToView(parentView, rightMargin)
        .heightIs(emptyHeight)
        .bottomEqualToView(parentView);
    }
//    [HKUIUtils addLineInView:view color:colorWithHex(0xe5e5e5) top:YES leftMargin:0 rightMargin:0];
    
    return view;
}


+ (__kindof UIView *) addVerticalLineInView:(UIView *)parentView
                                      right:(BOOL)isRight
                                  topMargin:(CGFloat)topMargin
                               bottomMargin:(CGFloat)bottomMargin
{
    LSYNLineView *line = [[LSYNLineView alloc] initGrayLineWithFrame:CGRectMake(0, 0, 1, parentView.height) vertical:YES isFirstPixelOpaque:!isRight];
    [parentView addSubview:line];

    if (isRight) {
        line.sd_layout
        .topSpaceToView(parentView, topMargin)
        .bottomSpaceToView(parentView, bottomMargin)
        .rightEqualToView(parentView)
        .heightIs(1);
    }else{
        line.sd_layout
        .topSpaceToView(parentView, topMargin)
        .bottomSpaceToView(parentView, bottomMargin)
        .leftEqualToView(parentView)
        .heightIs(1);
    }

    return line;
}

+ (__kindof UIView *) addVerticalLineInView:(UIView *)parentView
                                      right:(BOOL)isRight
                                      color:(UIColor *)color
                                  topMargin:(CGFloat)topMargin
                               bottomMargin:(CGFloat)bottomMargin
{
    LSYNLineView *line = [[LSYNLineView alloc] initWithFrame:CGRectMake(0, 0, 1, parentView.height) vertical:YES isFirstPixelOpaque:!isRight lineColor:color];
    [parentView addSubview:line];
    
    if (isRight) {
        line.sd_layout
        .rightEqualToView(parentView)
        .topSpaceToView(parentView, topMargin)
        .bottomSpaceToView(parentView, bottomMargin)
        .widthIs(1);
    }else{
        line.sd_layout
        .leftEqualToView(parentView)
        .topSpaceToView(parentView, topMargin)
        .bottomSpaceToView(parentView, bottomMargin)
        .widthIs(1);
        
    }
    
    return line;
}



/**
 *  通过 CAShapeLayer 方式绘制虚线
 *
 *  param lineView:       需要绘制成虚线的view
 *  param lineLength:     虚线的宽度
 *  param lineSpacing:    虚线的间距
 *  param lineColor:      虚线的颜色
 *  param lineDirection   虚线的方向  YES 为水平方向， NO 为垂直方向
 **/
+ (void)drawLineOfDashByCAShapeLayer:(UIView *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor lineDirection:(BOOL)isHorizonal {
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    
    [shapeLayer setBounds:lineView.bounds];
    
    if (isHorizonal) {
        
        [shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame) / 2, CGRectGetHeight(lineView.frame))];
        
    } else{
        [shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame) / 2, CGRectGetHeight(lineView.frame)/2)];
    }
    
    [shapeLayer setFillColor:[UIColor clearColor].CGColor];
    //  设置虚线颜色为blackColor
    [shapeLayer setStrokeColor:lineColor.CGColor];
    //  设置虚线宽度
    if (isHorizonal) {
        [shapeLayer setLineWidth:CGRectGetHeight(lineView.frame)];
    } else {
        
        [shapeLayer setLineWidth:CGRectGetWidth(lineView.frame)];
    }
    [shapeLayer setLineJoin:kCALineJoinRound];
    //  设置线宽，线间距
    [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineLength], [NSNumber numberWithInt:lineSpacing], nil]];
    //  设置路径
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 0, 0);
    
    if (isHorizonal) {
        CGPathAddLineToPoint(path, NULL,CGRectGetWidth(lineView.frame), 0);
    } else {
        CGPathAddLineToPoint(path, NULL, 0, CGRectGetHeight(lineView.frame));
    }
    
    [shapeLayer setPath:path];
    CGPathRelease(path);
    //  把绘制好的虚线添加上来
    [lineView.layer addSublayer:shapeLayer];
}

+ (UIImage *)imageWithLineWithImageView:(UIImageView *)imageView
{
    CGFloat width = imageView.frame.size.width;
    CGFloat height = imageView.frame.size.height;
    UIGraphicsBeginImageContext(imageView.frame.size);
    [imageView.image drawInRect:CGRectMake(0, 0, width, height)];
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    CGFloat lengths[] = {10,5};
    CGContextRef line = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(line, [UIColor colorWithRed:133/255.0 green:133/255.0 blue:133/255.0 alpha:1.0].CGColor);
    CGContextSetLineDash(line, 0, lengths, 1);
    CGContextMoveToPoint(line, 0, 1);
    CGContextAddLineToPoint(line, width-10, 1);
    CGContextStrokePath(line);
    return  UIGraphicsGetImageFromCurrentImageContext();
}


/**
 *  获得某个范围内的屏幕图像
 *
 *  @param theView View
 *  @param frame   frame
 *
 *  @return Image
 */
+ (UIImage *)getImageFromView:(UIView *)theView atFrame:(CGRect)frame
{
    NSParameterAssert(theView);
    //截取一部分
    //    UIView *view = [theView viewWithTag:100];
    //     *btn = [theView viewWithTag:101];
    //    [view setHidden:YES];
    //    [btn setHidden:NO];
    [[theView layer] setCornerRadius:0.0];
    [[theView layer] setMasksToBounds:NO];
    
    UIGraphicsBeginImageContextWithOptions(theView.size, NO, [UIScreen mainScreen].scale);
    //    if (IOS7) {
    //        [theView drawViewHierarchyInRect:theView.bounds afterScreenUpdates:YES];
    //    }else {
    //        theView.layer.contentsScale = [UIScreen mainScreen].scale;
    //        [theView.layer renderInContext:UIGraphicsGetCurrentContext()];
    //    }
    
    theView.layer.contentsScale = [UIScreen mainScreen].scale;
    [theView.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    theImage = [self clipRoundImageWithImage:theImage
                                       frame:CGRectMake(0, 0, frame.size.width, frame.size.height)
                                      Radius:theView.layer.cornerRadius
                                 StrokeColor:[UIColor clearColor]];
    
    //    [view setHidden:NO];
    //    [btn setHidden:YES];
    [[theView layer] setCornerRadius:8.0];
    [[theView layer] setMasksToBounds:YES];
    
    return theImage;
}

/**
 *  UIView提取Image
 *
 *  @param theView View
 *
 *  @return Image
 */
+ (UIImage *)getImageFromView:(UIView *)theView
{
    UIImage *img = nil;
    if(!CGSizeEqualToSize(theView.size, CGSizeZero))
    {
        UIGraphicsBeginImageContextWithOptions(theView.size, NO, [UIScreen mainScreen].scale);
        if (IOS7) {
            if(![theView drawViewHierarchyInRect:theView.bounds afterScreenUpdates:YES]) {
                theView.layer.contentsScale = [UIScreen mainScreen].scale;
                [theView.layer renderInContext:UIGraphicsGetCurrentContext()];
            }
        }else {
            theView.layer.contentsScale = [UIScreen mainScreen].scale;
            [theView.layer renderInContext:UIGraphicsGetCurrentContext()];
        }
        
        img = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    
    return img;
}

+ (UIImage *)getScreenImageFromView:(UIScrollView *)currentScrollView
{
    UIImage *image = nil;
    UIGraphicsBeginImageContext(currentScrollView.contentSize);
    {
        //        CGPoint savedContentOffset = currentScrollView.contentOffset;
        //        CGRect savedFrame = currentScrollView.frame;
        
        currentScrollView.frame = CGRectMake(0,0, currentScrollView.contentSize.width, currentScrollView.contentSize.height);
        
        
        [currentScrollView.layer renderInContext: UIGraphicsGetCurrentContext()];
        image = UIGraphicsGetImageFromCurrentImageContext();
        
        //        currentScrollView.contentOffset = savedContentOffset;
        //        currentScrollView.frame = savedFrame;
    }
    UIGraphicsEndImageContext();
    
    return image;
}

+ (UIImage*) clipRoundImageWithImage:(UIImage*)origImage
                               frame:(CGRect)frame
                              Radius:(CGFloat)r
                         StrokeColor:(UIColor *)strokeColor
{
    if (!origImage || CGSizeEqualToSize(origImage.size, CGSizeZero)) {
        return nil;
    }
    
    UIBezierPath *clipPath = [UIBezierPath bezierPathWithRoundedRect:frame cornerRadius:r];
    UIBezierPath *roundPath = clipPath;
    
    UIGraphicsBeginImageContextWithOptions(frame.size, NO, 0.0);
    {
        clipPath.usesEvenOddFillRule = YES;
        
        if (strokeColor) {
            [roundPath setLineWidth:1.0f];
            [strokeColor set];
            [roundPath stroke];
        }
    }
    [clipPath addClip];
    
    [origImage drawInRect:CGRectMake(0, 0, origImage.size.width, origImage.size.height)];
    UIImage* result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return result;
}


/**
 *  @brief  裁剪出无锯齿圆角 Cover
 *  @param r            半径
 *  @param strokeColor  描边颜色
 *
 *  @return 裁剪后得到的无锯齿圆角 Cover
 */
+ (UIImage*) clipRoundImageWithImage:(UIImage*)origImage
                            CutOuter:(BOOL)isCutOuter
                              Radius:(CGFloat)r
                         StrokeColor:(UIColor *)strokeColor
{
    if (!origImage || CGSizeEqualToSize(origImage.size, CGSizeZero)) {
        return nil;
    }
    
    CGRect rect = (CGRect){CGPointZero, origImage.size};
    
    UIBezierPath *clipPath = nil;
    UIBezierPath *roundPath = nil;
    
    if (isCutOuter) {
        clipPath = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:r];
        roundPath = clipPath;
    }else{
        clipPath = [UIBezierPath bezierPathWithRect:CGRectInfinite];
        roundPath = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:r];
        [clipPath appendPath:roundPath];
    }
    
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0);
    {
        clipPath.usesEvenOddFillRule = YES;
        
        if (!isCutOuter) {
            [UIColor.clearColor setFill];
            [roundPath fill];
        }
        
        if (strokeColor) {
            [roundPath setLineWidth:1.0f];
            [strokeColor set];
            [roundPath stroke];
        }
    }
    [clipPath addClip];
    
    [origImage drawInRect:rect];
    UIImage* result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return result;
}

+ (UIImage*) clipRoundImageWithImage:(UIImage*)origImage
                            CutOuter:(BOOL)isCutOuter
                              Radius:(CGFloat)r
                         StrokeColor:(UIColor *)strokeColor
                     StrokeLineWidth:(CGFloat)lineWidth{
    
    if (!origImage || CGSizeEqualToSize(origImage.size, CGSizeZero)) {
        return nil;
    }
    
    CGRect rect = (CGRect){CGPointZero, origImage.size};
    
    UIBezierPath *clipPath = nil;
    UIBezierPath *roundPath = nil;
    
    if (isCutOuter) {
        clipPath = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:r];
        roundPath = clipPath;
    }else{
        clipPath = [UIBezierPath bezierPathWithRect:CGRectInfinite];
        roundPath = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:r];
        [clipPath appendPath:roundPath];
    }
    
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0);
    {
        clipPath.usesEvenOddFillRule = YES;
        
        if (!isCutOuter) {
            [UIColor.clearColor setFill];
            [roundPath fill];
        }
        
        if (strokeColor) {
            [roundPath setLineWidth:lineWidth];
            [strokeColor set];
            [roundPath stroke];
        }
    }
    [clipPath addClip];
    
    [origImage drawInRect:rect];
    UIImage* result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return result;
}



/**
 *  获取圆角蒙版Image 永久保存内存
 *
 *  @param size   大小
 *  @param radius 圆角
 *  @param color  蒙版颜色
 *
 *  @return Image
 */
+ (UIImage *)getRoundImageWithCutOuter:(BOOL)isCutOuter
                                  Size:(CGSize)size
                                Radius:(CGFloat)radius
                                 color:(UIColor *)color
                       withStrokeColor:(UIColor *)strokeColor
{
    static NSMutableArray *cacheArray = nil;
    UIImage *retImage =  nil;
    roundMarkCacheKey *cacheKey = nil;
    
    if(!cacheArray) cacheArray = [NSMutableArray new];
    
    for(roundMarkCacheKey *tmp in cacheArray)
    {
        if((CGSizeEqualToSize(tmp.size, size)) &&
           (tmp.radius == radius) &&
           ([tmp.color isEqual:color]))
        {
            cacheKey = tmp;
            break;
        }
    }
    
    if(!cacheKey)
    {
        UIView *roundView = [UIView new];
        roundView.backgroundColor = color;
        [roundView setFrame:(CGRect){0,0,size.width+2, size.height+2}];
        
        retImage = [self getImageFromView:roundView atFrame:(CGRect){0, 0, size}];
        retImage = [self clipRoundImageWithImage:retImage CutOuter:isCutOuter Radius:radius StrokeColor:strokeColor];
        
        cacheKey = [roundMarkCacheKey new];
        cacheKey.size = size;
        cacheKey.radius = radius;
        cacheKey.color = color;
        cacheKey.image = retImage;
        
        [cacheArray addObject:cacheKey];
    }
    else
    {
        retImage = cacheKey.image;
    }
    
    return retImage;
}

+ (UIView *)getRoundViewAndLayerBoredWith:(UIView *)soureView
                                    radiu:(CGFloat )radiu
                                boreColor:(UIColor *)color{
    
    [soureView layoutIfNeeded];
    
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:soureView.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(radiu, radiu)];
    
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];
    //设置大小
    maskLayer.frame = soureView.bounds;
    //设置图形样子
    maskLayer.path = maskPath.CGPath;
    soureView.layer.mask = maskLayer;
    
    
    CAShapeLayer *borderLayer = [CAShapeLayer layer];
    borderLayer.bounds = CGRectMake(0, 0, soureView.width, soureView.height);
    borderLayer.position = CGPointMake(CGRectGetMidX(soureView.bounds), CGRectGetMidY(soureView.bounds));
    
    //    borderLayer.path = [UIBezierPath bezierPathWithRect:borderLayer.bounds].CGPath;
    //        borderLayer.path = [UIBezierPath bezierPathWithRoundedRect:borderLayer.bounds cornerRadius:CGRectGetWidth(borderLayer.bounds)/2].CGPath;
    borderLayer.path = [UIBezierPath bezierPathWithRoundedRect:borderLayer.bounds cornerRadius:radiu].CGPath;
    borderLayer.lineWidth = 1. / [[UIScreen mainScreen] scale];
    //虚线边框
    //        borderLayer.lineDashPattern = @[@8, @8];
    //实线边框
    borderLayer.lineDashPattern = nil;
    borderLayer.fillColor = [UIColor clearColor].CGColor;
    borderLayer.strokeColor = color.CGColor;
    [soureView.layer addSublayer:borderLayer];
    
    return soureView;
    
}

/**
 *  生成用于拉伸的UIImage图 (2x1 Or 1*2)像素永久保存内存
 *
 *  @param isVertical      是否垂直拉伸
 *  @param isFirstOpaque   是否第一像素不透明
 *  @param highlightColor  显示的颜色
 *
 *  @return image
 */
+ (UIImage *)getLineImageWithIsVertical:(BOOL)isVertical
                     isFirstPixelOpaque:(BOOL)isFirstOpaque
                         highlightColor:(UIColor *)highlightColor;
{
    static NSMutableArray *cacheArray = nil;
    
    UIImage *retImage = nil;
    lineImageCacheKey *cacheKey = nil;
    
    if(cacheArray) cacheArray = [NSMutableArray new];
    
    for(lineImageCacheKey *tmp in cacheArray)
    {
        if((tmp.isVertical == isVertical) &&
           (tmp.highlightColor == highlightColor) &&
           (tmp.isFirstPixelOpaque == isFirstOpaque))
        {
            cacheKey = tmp;
            break;
        }
    }
    
    if(!cacheKey)
    {
        CGSize vSize = isVertical?(CGSize){2, 1}:(CGSize){1, 2};
        
        UIGraphicsBeginImageContext(vSize);
        
        //创建路径并获取句柄
        CGMutablePathRef path = CGPathCreateMutable();
        
        CGFloat leftMargin = isVertical&&!isFirstOpaque ? 1:0;
        CGFloat topMargin = !isVertical&&!isFirstOpaque ? 1:0;
        
        //指定矩形
        CGRect rectangle = (CGRect){leftMargin,topMargin, 1, 1};
        
        //将矩形添加到路径中
        CGPathAddRect(path,NULL, rectangle);
        
        //获取上下文
        CGContextRef currentContext = UIGraphicsGetCurrentContext();
        
        //将路径添加到上下文
        CGContextAddPath(currentContext,path);
        
        //设置矩形填充色
        [highlightColor setFill];
        
        //矩形边框颜色
        [[UIColor clearColor] setStroke];
        
        //绘制
        CGContextDrawPath(currentContext,kCGPathFillStroke);
        
        CGPathRelease(path);
        
        retImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        cacheKey = [lineImageCacheKey new];
        cacheKey.isVertical = isVertical;
        cacheKey.isFirstPixelOpaque = isFirstOpaque;
        cacheKey.highlightColor = highlightColor;
        cacheKey.image = retImage;
        
        [cacheArray addObject:cacheKey];
    }
    else
    {
        retImage = cacheKey.image;
    }
    
    return retImage;
}

+ (UIImage *)getImageWithImage:(UIImage *)image
                          text:(NSString *)text
                     attribute:(NSDictionary *)attr
                        InRect:(CGRect)rect{
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
    [image drawAtPoint:CGPointZero];
    
    [text drawInRect:rect withAttributes:attr];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
    
    
}






+ (void)setRoundingCorners:(UIView *)view withCornerRadius:(CGFloat)radius
{
    CAShapeLayer *maskLayer = [HKUIUtils makeShapelayerWithRoundingCorners:UIRectCornerAllCorners
                                                                    forView:view
                                                           withCornerRadius:radius];
    
    view.layer.mask = maskLayer;
}


+ (void)setTopRoundingCorners:(UIView *)view withCornerRadius:(CGFloat)radius
{
    CAShapeLayer *maskLayer = [HKUIUtils makeShapelayerWithRoundingCorners:(UIRectCornerTopLeft|
                                                                             UIRectCornerTopRight)
                                                                    forView:view
                                                           withCornerRadius:radius];
    view.layer.mask = maskLayer;
}

+ (void)setBottomRoundingCorners:(UIView *)view withCornerRadius:(CGFloat)radius
{
    CAShapeLayer *maskLayer = [HKUIUtils makeShapelayerWithRoundingCorners:(UIRectCornerBottomLeft|
                                                                             UIRectCornerBottomRight)
                                                                    forView:view
                                                           withCornerRadius:radius];
    view.layer.mask = maskLayer;
}

+ (void)setLeftRoundingCorners:(UIView *)view withCornerRadius:(CGFloat)radius
{
    CAShapeLayer *maskLayer = [HKUIUtils makeShapelayerWithRoundingCorners:(UIRectCornerTopLeft|
                                                                             UIRectCornerBottomLeft)
                                                                    forView:view
                                                           withCornerRadius:radius];
    
    view.layer.mask = maskLayer;
}

+ (void)setRightRoundingCorners:(UIView *)view withCornerRadius:(CGFloat)radius
{
    CAShapeLayer *maskLayer = [HKUIUtils makeShapelayerWithRoundingCorners:(UIRectCornerTopRight  |
                                                                             UIRectCornerBottomRight)
                                                                    forView:view
                                                           withCornerRadius:radius];
    view.layer.mask = maskLayer;
}

+ (CAShapeLayer *)makeShapelayerWithRoundingCorners:(UIRectCorner)corners
                                            forView:(UIView*)view
                                   withCornerRadius:(CGFloat)radius
{
    UIBezierPath * bezierPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds
                                                      byRoundingCorners:corners
                                                            cornerRadii:CGSizeMake(radius, radius)];
    CAShapeLayer *corBoundmaskLayer = [CAShapeLayer layer];
    corBoundmaskLayer.frame         = view.bounds;
    corBoundmaskLayer.path          = bezierPath.CGPath;
    
    return corBoundmaskLayer;
}

+ (UIImage *)getImageWithRoundingCorners:(UIRectCorner)corners
                            cornerRadius:(CGFloat)radius
                                   frame:(CGRect)frame
                         backgroundcolor:(UIColor *)backgroundcolor
                             strokeColor:(UIColor *)strokeColor
                               lineWidth:(CGFloat)lineWidth
{
    UIImage *retImage =  nil;
    //    UIImage *originImage = [UIImage imageWithColor:backgroundcolor withFrame:frame];
    ////
    //    UIBezierPath * clipPath = [UIBezierPath bezierPathWithRoundedRect:frame
    //                                                    byRoundingCorners:corners
    //                                                          cornerRadii:CGSizeMake(radius, radius)];
    //
    //    retImage = [self clipImageWithOrigImage:originImage
    //                                   CutOuter:YES
    //                                   ClipPath:clipPath
    //                               CornerRadius:radius
    //                                      Color:backgroundcolor
    //                                StrokeColor:strokeColor
    //                                  LineWidth:lineWidth];
    
    return retImage;
}

//LSYLubtitleView 有使用
+ (UIImage *)clipImageWithRoundingCorners:(UIRectCorner)corners
                                  ForView:(UIView*)view
                             CornerRadius:(CGFloat)radius
                                    Color:(UIColor *)color
                              StrokeColor:(UIColor *)strokeColor
                                LineWidth:(CGFloat)lineWidth
{
    
    UIImage *retImage =  nil;
    UIView *roundView = [UIView new];
    roundView.backgroundColor = color;
    [roundView setFrame:view.bounds];
    
    retImage = [self getImageFromView:roundView atFrame:roundView.bounds];
    
    UIBezierPath * clipPath = [UIBezierPath bezierPathWithRoundedRect:roundView.frame
                                                    byRoundingCorners:corners
                                                          cornerRadii:CGSizeMake(radius, radius)];
    
    retImage = [self clipImageWithOrigImage:retImage
                                   CutOuter:YES
                                   ClipPath:clipPath
                               CornerRadius:radius
                                      Color:color
                                StrokeColor:strokeColor
                                  LineWidth:lineWidth];
    
    retImage = [self clipImageWithOrigImage:retImage
                                   CutOuter:NO
                                   ClipPath:clipPath
                               CornerRadius:radius
                                      Color:color
                                StrokeColor:strokeColor
                                  LineWidth:lineWidth];
    
    return retImage;
}

+ (UIImage *)clipImageWithOrigImage:(UIImage *)origImage
                           CutOuter:(BOOL)isCutOuter
                           ClipPath:(UIBezierPath *)clipPath
                       CornerRadius:(CGFloat)radius
                              Color:(UIColor *)color
                        StrokeColor:(UIColor *)strokeColor
                          LineWidth:(CGFloat)lineWidth
{
    if (!origImage || CGSizeEqualToSize(origImage.size, CGSizeZero)) {
        return nil;
    }
    
    CGRect rect = (CGRect){CGPointZero, origImage.size};
    
    UIBezierPath *outPath = [UIBezierPath bezierPathWithRect:CGRectInfinite];
    
    if (!isCutOuter) {
        [outPath appendPath:clipPath];
    }
    
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0);
    {
        clipPath.usesEvenOddFillRule = YES;
        
        if (!isCutOuter) {
            [[UIColor clearColor] setFill];
            [outPath fill];
        }
        
        if (strokeColor && isCutOuter) {
            [clipPath setLineWidth:lineWidth];
            [strokeColor set];
            [clipPath stroke];
        }
    }
    [clipPath addClip];
    
    [origImage drawInRect:rect];
    UIImage* result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return result;
}

+ (UIImage *)scaleImageToSize:(UIImage *)image scaleRate:(CGFloat)scaleRate {
    
    CGSize newSize = CGSizeMake(image.size.width * scaleRate, image.size.height * scaleRate);
    
    UIImage *newImage = [self oldScaleImageToSize:image size:newSize];
    
    return newImage;
}

+ (UIImage *)scaleImageToSize:(UIImage *)img size:(CGSize)size {
    
    UIImage *newImage = [self oldScaleImageToSize:img size:size];
    
    return newImage;
}

+ (UIImage *)oldScaleImageToSize:(UIImage *)img size:(CGSize)size {
    
    //零大小 不处理
    if (CGSizeEqualToSize(CGSizeZero, size)) {
        return img;
    }
    
    CGFloat targetWidth = size.width;
    CGFloat targetHeight = size.height;
    
    CGImageRef imageRef = [img CGImage];
    
    // by sam
    CGColorSpaceRef colorSpaceInfo = CGColorSpaceCreateDeviceRGB();
    CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
    
    CGContextRef bitmap = CGBitmapContextCreate(NULL, targetWidth, targetHeight, 8, 4 * targetWidth, colorSpaceInfo, bitmapInfo);
    
    if(!bitmap) {
        
        targetWidth = img.size.width;
        targetHeight = img.size.height;
        bitmap = CGBitmapContextCreate(NULL, targetWidth, targetHeight, 8, 4 * targetWidth, colorSpaceInfo, bitmapInfo);
    }
    
    CGContextDrawImage(bitmap, CGRectMake(0, 0, targetWidth,targetHeight), imageRef);
    CGImageRef ref = CGBitmapContextCreateImage(bitmap);
    UIImage* newImage = [UIImage imageWithCGImage:ref];
    
    CGColorSpaceRelease(colorSpaceInfo);
    CGContextRelease(bitmap);
    CGImageRelease(ref);
    
    return newImage;
}

+ (UIImage *)newScaleImageToSize:(UIImage *)img size:(CGSize)size {
    
    //    NSDate *date = [NSDate date];
    
    CVPixelBufferRef pixelBuffer = [self pixelBufferFromCGImage:img.CGImage andSize:size];
    //    NSLog(@"pixelBufferFromCGImage--sec-%f",[[NSDate date] timeIntervalSinceDate:date]);
    
    UIImage *outputImage = nil;
    
    if (pixelBuffer) {
        int w = (int)CVPixelBufferGetWidth(pixelBuffer);
        int h = (int)CVPixelBufferGetHeight(pixelBuffer);
        int r = (int)CVPixelBufferGetBytesPerRow(pixelBuffer);
        int bytesPerPixel = r/w;
        
        CVPixelBufferLockBaseAddress(pixelBuffer,0);
        unsigned char *buffer=malloc(CVPixelBufferGetDataSize(pixelBuffer));
        memcpy(buffer,CVPixelBufferGetBaseAddress(pixelBuffer),CVPixelBufferGetDataSize(pixelBuffer) );
        CVPixelBufferUnlockBaseAddress(pixelBuffer,0);
        
        UIGraphicsBeginImageContext(CGSizeMake(w, h));
        CGContextRef c = UIGraphicsGetCurrentContext();
        unsigned char* data = CGBitmapContextGetData(c);
        if (data != NULL) {
            int maxY = h;
            for(int y = 0; y<maxY; y++) {
                for(int x = 0; x<w; x++) {
                    int offset = bytesPerPixel*((w*y)+x);
                    data[offset] = buffer[offset];     // R
                    data[offset+1] = buffer[offset+1]; // G
                    data[offset+2] = buffer[offset+2]; // B
                    data[offset+3] = buffer[offset+3]; // A
                }
            }
        }
        outputImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        free(buffer);
    }
    
    return outputImage;
}


+ (CVPixelBufferRef)pixelBufferFromCGImage:(CGImageRef)image andSize:(CGSize)size {
    @autoreleasepool {
        //        NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
        //                                 [NSNumber numberWithBool:NO],     kCVPixelBufferCGImageCompatibilityKey,
        //                                 [NSNumber numberWithBool:NO],     kCVPixelBufferCGBitmapContextCompatibilityKey,
        //                                 nil];
        CVPixelBufferRef pxbuffer = NULL;
        
        //        CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault, size.width,
        //                                              size.height, kCVPixelFormatType_32ARGB, (__bridge CFDictionaryRef) options,
        //                                              &pxbuffer);
        //        NSParameterAssert(status == kCVReturnSuccess && pxbuffer != NULL);
        
        CVPixelBufferLockBaseAddress(pxbuffer, 0);
        void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer);
        NSParameterAssert(pxdata != NULL);
        
        CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
        CGContextRef context = CGBitmapContextCreate(pxdata, size.width, size.height, 8,     4*size.width, rgbColorSpace, (CGBitmapInfo)kCGImageAlphaPremultipliedLast);
        
        NSParameterAssert(context);
        CGContextConcatCTM(context, CGAffineTransformMakeRotation(0));
        CGContextDrawImage(context, CGRectMake(0, 0, size.width, size.height), image);
        CGColorSpaceRelease(rgbColorSpace);
        CGContextRelease(context);
        
        CVPixelBufferUnlockBaseAddress(pxbuffer, 0);
        
        return pxbuffer;
    }
}

+ (void)setImageUpAndTitleDownStyleFor:(UIButton *)button withImageAndTitleMargin:(CGFloat)margin
{
    CGPoint buttonBoundsCenter    = CGPointMake(CGRectGetMidX(button.bounds), CGRectGetMidY(button.bounds));
    CGPoint endImageViewCenter    = CGPointMake(buttonBoundsCenter.x, CGRectGetMidY(button.imageView.bounds));
    CGPoint endTitleLabelCenter   = CGPointMake(buttonBoundsCenter.x,
                                                CGRectGetHeight(button.bounds)-
                                                CGRectGetMidY(button.titleLabel.bounds));
    
    CGPoint startImageViewCenter  = button.imageView.center;
    CGPoint startTitleLabelCenter = button.titleLabel.center;
    CGFloat imageEdgeInsetsTop    = -margin;
    CGFloat imageEdgeInsetsLeft   = endImageViewCenter.x - startImageViewCenter.x;
    CGFloat imageEdgeInsetsBottom = -imageEdgeInsetsTop;
    CGFloat imageEdgeInsetsRight  = -imageEdgeInsetsLeft;
    
    button.imageEdgeInsets        = UIEdgeInsetsMake(imageEdgeInsetsTop,
                                                     imageEdgeInsetsLeft,
                                                     imageEdgeInsetsBottom,
                                                     imageEdgeInsetsRight);
    
    CGFloat titleEdgeInsetsTop    = ceilf(fabs(margin)*2)+2;
    CGFloat titleEdgeInsetsLeft   = endTitleLabelCenter.x - startTitleLabelCenter.x;
    CGFloat titleEdgeInsetsBottom = -titleEdgeInsetsTop;
    CGFloat titleEdgeInsetsRight  = -titleEdgeInsetsLeft;
    
    button.titleEdgeInsets = UIEdgeInsetsMake(titleEdgeInsetsTop,
                                              titleEdgeInsetsLeft,
                                              titleEdgeInsetsBottom,
                                              titleEdgeInsetsRight);
}


@end

